"""
Case Type   : 服务端工具
Case Name   : 验证gs_restore工具功能
Create At   : 2024.10.8
Owner       : wang-tianjing1
Description :
    1.显示帮助信息
    2.显示版本信息
    3.导入数据
    4.清理环境
Expect      :
    1.显示正确
    2.显示正确
    3.成功
    4.成功
History     :
"""
import unittest
import os
from yat.test import Node
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger




class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_node = Node('PrimaryDbUser')
        self.root_node = Node('default')
        self.constant = Constant()

    def test_server_tools1(self):
        self.log.info('-------step1:显示帮助信息;except:显示正确--------')
        cmd_list = ['-?', '--help']
        for cmd in cmd_list:
            check_cmd1 = f'''source {macro.DB_ENV_PATH}
                 gs_restore {cmd}'''
            self.log.info(check_cmd1)
            msg1 = self.primary_node.sh(check_cmd1).result()
            self.log.info(msg1)
            self.log.info('--------------校验语法------------------')
            self.assertIn('gs_restore [OPTION]... FILE', msg1)
            self.log.info('-------------截取General options:后面的参数-------------------')
            start_index1 = msg1.find('General options:')
            self.log.info('--------------定义一个空的列表，将获取的参数写入这个列表，并打印出该列表-------------------')
            options_list1 = []
            for i in msg1[start_index1:].split('\n'):
                for j in i.split(' '):
                    if len(j) != 0:
                        if j[0] == '-':
                            options_list1.append(j)
                        else:
                            pass
                    else:
                        pass
            self.log.info(options_list1)
            self.log.info('--------------判断参数存在与否-------------------')
            parameter = [
                '-d,', '--dbname=NAME', '-f,', '--file=FILENAME', '-F,', '--format=c|d|t', '-l,', '--list',
                '-v,', '--verbose', '-V,', '--version', '-?,', '--help', '-a,', '--data-only', '-c,', '--clean',
                '-C,', '--create', '-e,', '--exit-on-error', '-I,', '--index=NAME', '-j,', '--jobs=NUM', '-L,',
                '--use-list=FILENAME', '-n,', '--schema=NAME', '-O,', '--no-owner', '-P,', '--function=NAME(args)',
                '-s,', '--schema-only', '-S,', '--sysadmin=NAME', '-t,', '--table=NAME', '-T,', '--trigger=NAME',
                '-x,', '--no-privileges/--no-acl', '-1,', '--single-transaction', '--disable-triggers',
                '--no-data-for-failed-tables', '--no-security-labels', '--no-tablespaces', '--section=SECTION',
                '--use-set-session-authorization', '--with-key=KEY', '-h,', '--host=HOSTNAME', '-p,',
                '--port=PORT', '-U,', '--username=NAME', '-w,', '--no-password', '-W,', '--password=PASSWORD',
                '--role=ROLENAME', '--rolepassword=ROLEPASSWORD']
            if len(options_list1) == len(parameter):
                for opt in options_list1:
                    if opt in parameter:
                        self.log.info(f'{opt}---------参数校验通过---------')
                    else:
                        self.log.error(f'{opt}---------参数校验不通过---------')
            else:
                self.log.error('---------参数校验有误---------')

        self.log.info('--------step2:显示版本号信息;except:显示正确---------')
        cmd_list = ['-V', '--version']
        for cmd in cmd_list:
            check_cmd1 = f'''source {macro.DB_ENV_PATH}
                                gs_restore {cmd}'''
            self.log.info(check_cmd1)
            msg1 = self.primary_node.sh(check_cmd1).result()
            self.log.info(msg1)
            self.assertIn('openGauss', msg1)

        self.log.info("----------step3:导入数据;except:成功----------")
        self.log.info("--------------------创建表并插入数据--------------------")
        sql_cmd = f'''
                drop table if exists test;
                create table test (id  int,name char(20));
                insert into test values(1,'xixi'),(2,'haha'),(3,'hehe');
                '''
        excute_cmd = f'''
                source {macro.DB_ENV_PATH} ;
                gsql -d {self.primary_node.db_name} \
                -p {self.primary_node.db_port} -c "{sql_cmd}"
                '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg)

        self.log.info("----------------------创建角色-----------------------")
        sql_cmd = f'''
                create role manager identified by '{macro.COMMON_PASSWD}';'''
        excute_cmd = f'''
                source {macro.DB_ENV_PATH} ;
                gsql -d {self.primary_node.db_name} \
                -p {self.primary_node.db_port} -c "{sql_cmd}"
                '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, msg)

        self.log.info("----------------------创建表空间-----------------------")
        sql_cmd = f'''
                create tablespace ds_location1 relative \
                location 'tablespace/tablespace_1';
                alter tablespace ds_location1 rename to ds_location3;
                alter tablespace ds_location3 owner to manager;'''
        excute_cmd = f'''
                source {macro.DB_ENV_PATH} ;
                gsql -d {self.primary_node.db_name} -p {self.primary_node.db_port} \
                -c "{sql_cmd}"
                '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_ALTER_SUCCESS, msg)

        self.log.info("----------------------创建数据库-----------------------")
        sql_cmd = f'''
                drop database if exists res_test1;
                create database res_test1;
                create schema schema1;'''
        excute_cmd = f'''
                source {macro.DB_ENV_PATH} ;
                gsql -d {self.primary_node.db_name} -p {self.primary_node.db_port} \
                -c "{sql_cmd}"
                '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, msg)

        self.log.info("--------------------创建创建函数---------------------")
        sql_cmd = f'''
            create function func_increment_sql(i integer)
            returns integer
            as \$$
            begin
                return i+1;
            end;
            \$$ language plpgsql;
            '''
        excute_cmd = f'''
                    source {macro.DB_ENV_PATH} ;
                    gsql -d {self.primary_node.db_name} -p {self.primary_node.db_port} \
                    -c "{sql_cmd}"
                    '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, msg)

        self.log.info("------------------------导出数据-------------------------")
        check_cmd = f'''mkdir /home/test_restore/
                chmod -R 777 /home/test_restore/'''
        self.log.info(check_cmd)
        msg = self.root_node.sh(check_cmd).result()
        self.log.info(msg)
        check_cmd = f'''
            source {macro.DB_ENV_PATH}
            gs_dump  -p {self.primary_node.db_port} {self.primary_node.db_name} \
            -f /home/test_restore/test2 -F c ;
            '''
        self.log.info(check_cmd)
        msg = self.primary_node.sh(check_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.GS_DUMP_SUCCESS_MSG, msg)

        self.log.info("-----------------导入之前导出的数据------------------")
        check_cmd = f'''source {macro.DB_ENV_PATH}
        gs_restore -p {self.primary_node.db_port} -d {self.primary_node.db_name} \
        -W {self.primary_node.db_password}   /home/test_restore/test2 -c'''
        self.log.info(check_cmd)
        msg = self.primary_node.sh(check_cmd).result()
        self.log.info(msg)
        self.assertIn(self.constant.RESTORE_SUCCESS_MSG, msg)

    def tearDown(self):
        self.log.info("----------step4:清理环境;except:成功------------")
        sql_cmd = f'''
                drop table if exists test  CASCADE;
                drop tablespace if exists ds_location3;
                drop role if exists manager;
                drop database if exists res_test1 ;
                drop schema if exists schema1 cascade;
                drop function if exists func_increment_sql;
                '''
        excute_cmd = f'''
                source {macro.DB_ENV_PATH} ;
                gsql -d {self.primary_node.db_name} -p {self.primary_node.db_port} \
                -c "{sql_cmd}"
                '''
        self.log.info(excute_cmd)
        msg = self.primary_node.sh(excute_cmd).result()
        self.log.info(msg)
        check_cmd = f'''rm -rf /home/test_restore'''
        self.log.info(check_cmd)
        msg = self.root_node.sh(check_cmd).result()
        self.log.info(msg)
        self.log.info(f'-----{os.path.basename(__file__)} end------')